package fgoScript.service;

import ComPuter.entity.ComputerChain;
import commons.entity.Constant;
import commons.entity.CpMissonResults;
import commons.entity.NativeCp;
import commons.util.ProcessDealUtil;
import commons.util.PropertiesUtil;
import fgoScript.constant.GameConstant;
import fgoScript.entity.Gudazi;
import commons.util.GameUtil;
import gudaziEx.entity.RunningChain;
import gudaziEx.service.ClickManage;
import gudaziEx.util.ChainUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.support.CronTrigger;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ScheduledFuture;

public class TimerManager {
	private static final Logger LOGGER = LogManager.getLogger(TimerManager.class);
	// 计划任务对象
	private TaskScheduler scheduler;
	// 计划future对象
	private ScheduledFuture future;
	//
	private ThreadPoolTaskExecutor timerTaskExcutor;
    //
	private ClickManage clickManage;
	/** 前台线程 **/
	private ThreadPoolTaskExecutor frontExcutor;

	private Gudazi gudazi;
	public void setScheduler(TaskScheduler scheduler) {
		this.scheduler = scheduler;
	}

	public ScheduledFuture getFuture() {
		return future;
	}

	public void setFuture(ScheduledFuture future) {
		this.future = future;
	}

	public void setGudazi(Gudazi gudazi) {
		this.gudazi = gudazi;
	}

	public void setTimerTaskExcutor(ThreadPoolTaskExecutor timerTaskExcutor) {
		this.timerTaskExcutor = timerTaskExcutor;
	}

	public void setClickManage(ClickManage clickManage) {
		this.clickManage = clickManage;
	}

	public void setFrontExcutor(ThreadPoolTaskExecutor frontExcutor) {
		this.frontExcutor = frontExcutor;
	}

	public TimerManager() {
	}
	/**
	 * @Description: 启动定时任务
	 * @return: void
	 * @throw:
	 * @Author: RENZHEHAO
	 * @Date: 2019/5/22
	 */
	public void startTasks(){
		String gdzCornForStartGudazi = GameUtil.getValueFromConfig("gdzCornForStartGudazi");
		String gdzCornStringForCloseApp = GameUtil.getValueFromConfig("gdzCornForCloseApp");
		String gdzCornForShutDown = GameUtil.getValueFromConfig("gdzCornForShutDown");
		boolean ifMinMissionStart = Boolean.parseBoolean(PropertiesUtil.getValueFromFileNameAndKey("IF_MIN_MISSION", "DCinit", Constant.DC + "/"));
		boolean IF_LO = Boolean.parseBoolean(GameUtil.getValueFromConfig("IF_LO"));
		boolean IF_ShutDown_InTime = Boolean.parseBoolean(GameUtil.getValueFromConfig("IF_ShutDown_InTime"));
		boolean IF_CloseApp_InTime = Boolean.parseBoolean(GameUtil.getValueFromConfig("IF_CloseApp_InTime"));
		int PRINT_MINUTES = Integer.parseInt(GameUtil.getValueFromConfig("PRINT_MINUTES"));// 超时时间(分)
		int CHECK_MINUTES = Integer.parseInt(GameUtil.getValueFromConfig("CHECK_MINUTES"));//

		if (!"RZH_SERVER".equals(NativeCp.getUserName())) {
			if(false){
				scheduler.scheduleAtFixedRate(new Runnable() {
					@Override
					public void run() {
						ComputerChain.GoCheckTopToon();				}
				},  CHECK_MINUTES * 60 * 1000);
			}
			scheduler.scheduleAtFixedRate(new Runnable() {
				@Override
				public void run() {
					ComputerChain.GoCheckCpRunningState();				}
			},  CHECK_MINUTES * 60 * 1000);
			ComputerChain.GoCheckRest();
			LOGGER.info("用户名： " + NativeCp.getUserName() + "不启动检测任务");
		}else {

			CpMissonResults cr = CpMissonResults.getInstance();
			cr.setCpRunningDate(GameUtil.getNowDateString());
			cr.setCpRunningState(true);
			ChainUtil.saveCpMissonResults(cr);

			// 删除过期图片
			deletePics();
			//执行精简日常任务
			Calendar cd = Calendar.getInstance();
			int h = cd.get(Calendar.HOUR_OF_DAY);
//			if (ifMinMissionStart && (h < 2 || h > 6)) {
//				//5秒后执行 DC 任务
//				scheduler.scheduleAtFixedRate(new Runnable() {
//					@Override
//					public void run() {
//						DaillyMission dm = (DaillyMission) MySpringUtil.getApplicationContext().getBean("daillyMission");
//						dm.toggle(true);
//					}
//				},24 * 60 * 60 * 1000);
//			}else{
				//执行挂机任务
				scheduler.schedule(gudazi,new CronTrigger(gdzCornForStartGudazi));
//			}
			LOGGER.info("定时任务已启动！");
			//定时截图查看运行情况
			scheduler.scheduleAtFixedRate(new Runnable() {
				@Override
				public void run() {
					GameUtil.fullScreen2file(GameConstant.IMG_EXTEND, GameUtil.getPreFixNoDate() + "\\runningPic\\" + "running.");
				}
			},PRINT_MINUTES * 60 * 1000);
			//启动定时关机
			if(IF_ShutDown_InTime){
				scheduler.schedule(new Runnable() {
					@Override
					public void run() {
						ProcessDealUtil.closeComputerInTime(1);
					}
				}, new CronTrigger(gdzCornForShutDown));
			}
			//启动定时关脚本
			if(IF_CloseApp_InTime){
				scheduler.schedule(new Runnable() {
					@Override
					public void run() {
						try {
							ProcessDealUtil.killProc("javaw.exe");
						} catch (IOException e) {
							LOGGER.error(e.getMessage());
						}
//						ProcessDealUtil.closeComputerInTime(1);
					}
				}, new CronTrigger(gdzCornStringForCloseApp));
			}

			if(IF_LO){
				//启动刷训练本
				scheduler.schedule(new Runnable() {
					@Override
					public void run() {
						RunningChain rc = ChainUtil.getRunningChain();
						rc.setLogin(true);
						ChainUtil.saveRunningChain(rc);
						boolean ifGo = Gudazi.ifGoTrain();
						// DoSth
						if(ifGo && frontExcutor.getActiveCount() != 0){
							LOGGER.info("执行切出");
							clickManage.waitUntilShiftOut();
						}

						Gudazi.doLoTrain(ChainUtil.getRunningChain(),timerTaskExcutor,clickManage, Boolean.parseBoolean(GameUtil.getValueFromConfig("IF_LO")));

						if(ifGo){
							// 执行lo当前挂机任务
							LOGGER.info("开始返回挂机任务");
							timerTaskExcutor.execute(new Runnable() {
								@Override
								public void run() {
									clickManage.Toggle(ChainUtil.getRunningChain().getAutoChainName(),false);
								}
							});
						}
					}
				}, new CronTrigger("0 01 22 * * ?"));
			}

		}
	}
	private static void deleteDirs(File f){
		if (f.isDirectory()) {
			File [] b = f.listFiles();//获取包含file对象对应的子目录或者文件
			File temp;
			for(int i = 0; i< (b != null ? b.length : 0); i++){
				temp = b[i];
				if(temp.isFile()){//判断是否为文件
					temp.delete();//如果是就删除
					LOGGER.info("删除文件:" + temp.getName());
				}else{
					deleteDirs(temp);//否则重新递归到方法中
				}
			}
			f.delete();//最后删除该目录中所有文件后就删除该目录
			LOGGER.info("删除文件夹:" + f.getName());
		}
    }
	private static void deletePics() {
		try {
			String USERPROFILE = System.getenv("OneDrive");
			String ROOT_PATH = GameUtil.getValueFromConfig("ROOT_PATH");
			String path = USERPROFILE + ROOT_PATH;
			File file = new File(path);
			File[] files;
			boolean isDir = file.isDirectory();
			long nowTime = System.currentTimeMillis();
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			String nowString = sf.format(new Date(nowTime));
			if (isDir) {
				files  = file.listFiles();
				File temp;
				File inneFile;
				String fileString;
				String name;
				int loc;
				int tempFilesSize;
				File[] tempFiles;
				int rewardCounts;
				int filesLength = files != null ? files.length : 0;
				for (int i = 0; i < filesLength; i++) {
					temp = files[i];
					if (temp.isDirectory()) {
						name = temp.getName();
						tempFiles = temp.listFiles();
						tempFilesSize = tempFiles != null ? tempFiles.length : 0;
						loc = name.indexOf("_");
						if (loc != -1) {
							fileString= name.substring(0, name.indexOf("_"));
						}else {
							fileString = name;
						}
						if (nowString.equals(fileString)) {
							rewardCounts = 0;
							for (int j = 0; j < tempFilesSize; j++) {
								inneFile = tempFiles[j];
								if (inneFile.getName().contains("奖励")) {
									rewardCounts++;
								}
							}
							if (rewardCounts==0) {
								deleteDirs(temp);
							}
						}else {
							deleteDirs(temp);
						}
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error(GameUtil.getStackMsg(e));
		}
	}
	public void startTaskByTime(String time, Runnable runnable, String taskName){
		String[] times = time.split(":");
		String HOUR_OF_DAY = Integer.valueOf(times[0]) + "";
		String MINUTE = Integer.valueOf(times[1]) + "";
		String cornSting ="* " + MINUTE+ " " + HOUR_OF_DAY + " * * *";

		LOGGER.info("用户名: "+NativeCp.getUserName()+" 启动任务");

		setFuture(scheduler.schedule(runnable, new CronTrigger(cornSting)));
	}
	public void stopTask(String taskName){
		LOGGER.info("用户名: "+NativeCp.getUserName()+" 关闭任务");
		getFuture().cancel(false);
	}
}
